import { createContainer } from "unstated-next";
import { createSDK } from "../../sdk";
import { processStream, contextToString } from "../../utils/processStream";
import { useEffect, useState } from "react";
import { defs } from "../../sdk/type";

type MessageContextProps = {
  data: string;
} & undefined;

type modelType = "moonshot-v1-8k" | "moonshot-v1-32k" | "moonshot-v1-128k";

const Moonshot = createSDK({
  headers: {
    Authorization: "Bearer sk-VKFtOrKns8j7IJGcRPXvR2Cy0au5mDtDWc082NMj1iLVRkwF",
  },
});

const useMessageContext = () => {
  const [model, changeModel] = useState<modelType>("moonshot-v1-8k");

  const [messages, changeMessages] = useState<Array<defs.Dict>>([
    {
      role: "system",
      content:
        "你是 Kimi，由 Moonshot AI 提供的人工智能助手，你更擅长中文和英文的对话。你会为用户提供安全，有帮助，准确的回答。同时，你会拒绝一切涉及恐怖主义，种族歧视，黄色暴力等问题的回答。Moonshot AI 为专有名词，不可翻译成其他语言。",
    },
    {
      role: "user",
      content: "你好，我叫李雷，1+1等于多少？",
    },
  ]);

  const { data } = Moonshot.models.list.useRequest({});

  const responseMessage = (message: Array<defs.Dict>) => {
    Moonshot.chat.completions
      .request({
        messages: message,
        stream: true,
        temperature: 0.3,
        model: model,
      })
      .then((res) => {
        if (res.body) {
          processStream(res.body).then((data: any) => {
            console.log(data, contextToString(data));
          });
        }
      });
  };

  useEffect(() => {
    messages.forEach((item) => {
      responseMessage([item]);
    });
  }, [messages]);

  return {
    models: data?.data?.map((item) => item.owned_by),
  };
};

export const MessageContext = createContainer(useMessageContext);
